package main

import (
	"fmt"
)

// chan 练习 同时写入50  读取50次

var intChan chan int

func demo112() {
	intChan = make(chan int, 20)
	boolChan := make(chan bool, 1)
	intChan <- 1
	intChan <- 2
	fmt.Println(<-intChan)
	fmt.Println(<-intChan)

	go demo11Write(intChan)
	go demo11Read(intChan, boolChan)
	//defer close(intChan)
	defer close(boolChan)
	if <-boolChan {
		fmt.Println("写入结束")
	}
	//time.Sleep(time.Second * 2)
	fmt.Println("end")
}

func demo11Read(intChan <-chan int, boolChan chan<- bool) {
	for {
		v, ok := <-intChan
		if !ok {
			boolChan <- true // 读取结束，通知写入结束
			break
		}
		fmt.Printf("读取值：%d \n", v)
	}
	fmt.Println("读取结束")
}

func demo11Write(intChan chan<- int) {
	for i := 0; i < 10; i++ {
		intChan <- i
		fmt.Printf("写入值：%d \n", i)
	}
	close(intChan)
}
